package com.example.shengyin.controller;

import com.alibaba.fastjson2.JSON;
import com.example.shengyin.entity.Admin;
import com.example.shengyin.entity.Article;
import com.example.shengyin.entity.Attach;
import com.example.shengyin.entity.Page;
import com.example.shengyin.service.AttachService;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * SubjectController
 *
 * @author gyy
 * @date 2023-07-29
 */
@RestController
@RequestMapping("/attach")
@Validated
@CrossOrigin(origins = "*", maxAge = 3600, allowCredentials = "true")
//swagger
@Api("文章")
//redis缓存用
public class AttachController {
    @Autowired
    private AttachService service;
    @Value("${upload-path}")
    private String path;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询文章列表
     */
    @ApiOperation("上传文件列表")
    @GetMapping("/list")
    public Result list(Page page, @ApiParam(name = "attachuri", value = "地址") @RequestParam(required = false) String attachuri) {
        List<Attach> list = service.list(page, attachuri);
        int count = service.count(attachuri);
        //if (count == 0 || list == null)
        //    return Result.error(null);
        page.setData(list);
        page.setCount(count);
        System.out.println(JSON.toJSONString(Result.success(page)));
        return Result.success(page);
    }

    //    @GetMapping("/list")
//    public Page<Subject> list(@ApiParam(name = "page",value = "页") @RequestParam(required = false) int page,@ApiParam(name = "limit",value = "页") @RequestParam(required = false) int limit,@ApiParam(name = "cname",value = "课程名称") @RequestParam(required = false) String cname,
//                     @ApiParam(name = "poster",value = "发布人") @RequestParam(required = false) String poster)
//   {
//       Page<Subject> list = service.list(page, limit, cname, poster);
//       return list;
//
//   }
    @GetMapping(value = "/select/{id}")
    public Result select(@PathVariable(value = "id") Long id) {
        Attach select = service.select(id);
        if (select == null)
            return Result.error("没有找到数据");
        return Result.success(select);
    }

    @PostMapping("/add")
    public Result insert(@Valid Attach dAttach, BindingResult bindingResult) {
        int insert = service.insert(dAttach);
        if (insert == 0)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }

    @PostMapping("/edit")
    public Result edit(@Valid Attach dAttach, BindingResult bindingResult) {
        int insert = service.update(dAttach);
        if (insert == 0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }

    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable(value = "id") int id) {
        int delete = service.delete(id);
        if (delete == 0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }

    @GetMapping("/deleteByIds/{ids}")
    public Result deleteByIds(@PathVariable(value = "ids") String ids) {
        System.out.println("开始这些");
        String s = StrUtil.ListtoString(ids);
        int delete = service.deleteByIds(s);
        if (delete == 0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值 }
        //特殊的格式
        //SimpleDateFormat d2 = new SimpleDateFormat("yyyy/MM/dd");

        //binder.registerCustomEditor(Date.class,"birthday", new CustomDateEditor(d2, true));

    }

    //    @PostMapping("/upload")
//    public Result upload(@RequestParam(name="imgurlUpload")MultipartFile file){
//        Map<String,Object> m=new HashMap<>();
//        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
//        System.out.println("????>>>??????"+file);
//        if (file!=null &&!file.isEmpty()) {
//            File f = new File(path);
//            if (!f.exists())
//                f.mkdirs();
//            //原来的文件名
//            String filename = file.getOriginalFilename();
//            String houzhui = filename.substring(filename.lastIndexOf('.'));
//            String newName = UUID.randomUUID() + houzhui;
//            try {
//                file.transferTo(new File(f,newName));
//                m.put("code",0);
//                return Result.success(newName,"添加成功");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        m.put("code",415);
//        m.put("msg","图片没有选择");
//        return Result.error(415,"图片没有选择");
//    }
    @PostMapping("upload")
    @ApiOperation("图片上传文件方法")
    public Result upload(@RequestParam("imgurlUpload") MultipartFile file, HttpServletRequest request) {
        if (file != null && !file.isEmpty()) {
            try {
//            String webAppRoot = request.getServletContext().getRealPath("/");
//            String path = Paths.get(webAppRoot, "img").toString();
//                String path = Paths.get("img").toString();// 用来获取一个表示文件路径的字符串

                File f = new File(path);
                System.out.println(path);
                if (!f.exists())
                    f.mkdirs();

                String filename = file.getOriginalFilename();
                String houzhui = filename.substring(filename.lastIndexOf('.'));
                String newName = UUID.randomUUID() + houzhui;

                Files.copy(file.getInputStream(), Paths.get(f.getAbsolutePath(), newName));

                return Result.success("img/" + newName, "上传成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.error("上传失败");
    }
    @ApiOperation("显示")
    @GetMapping("/isvalue/{id}/{isvalue}")
    public Result edit(@PathVariable(value = "id") Long id,
                       @PathVariable(value = "isvalue")boolean isvalue,HttpServletRequest request)
    {
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        Attach attach=new Attach();
        System.out.println(id);
        attach.setId(id);
        System.out.println(isvalue);
        attach.setIsvalid(isvalue);
        attach.setPoster(admin.getRealname());
        attach.setPosttime(new Date());
        int insert = service.update(attach);

        if(insert==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }



    @PostMapping("/give")
    @ApiOperation("根据carousel查地址")
    public Result give(@ApiParam(name = "carousel", value = "轮播板块") @RequestParam(required = false)String carousel){
        List<String> give = service.give(carousel);
        return give==null?Result.success("无"):Result.success(give);
    }
}
